﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VIPJoystick : MonoBehaviour {

    [SerializeField]
    private Transform stick;
    [SerializeField]
    private Canvas canvas;

    //半径的最大值
    [SerializeField]
    private float maxRadius = 90; 

    private Vector2 stickDir = Vector2.zero;

    public Vector2 dir
    {
        get
        {
            return stickDir;
        }
    }

    /// <summary>
    /// 开始拖动
    /// </summary>
    public void OnStartDrag() {

    }

    /// <summary>
    /// 拖动中
    /// </summary>
    public void OnDrag()
    {
        Vector2 pos = Vector2.zero;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform,
            Input.mousePosition, canvas.worldCamera, out pos);
        //求得pos点距离父节点中心的距离---实际的半径
        float len = pos.magnitude;

      

        //cosα -1 1 ,归一化
        stickDir.x = pos.x / len;
        //sinα -1 1
        stickDir.y = pos.y / len;

        //90/len = x1 /x = y1 /y,相似三角形，对应边成比例
        if (len > maxRadius)
        {
            pos.x = pos.x * maxRadius / len;
            pos.y = pos.y * maxRadius / len;
        }

        print(pos);

        stick.localPosition = pos;
    }

    /// <summary>
    /// 结束拖动
    /// </summary>
    public void OnEndDrag()
    {
        stick.localPosition = Vector2.zero;
        stickDir = Vector2.zero;
    }

}
